<?php
namespace app\admin\logic;

use app\common\logic\Base;
use think\facade\App;

class AuthRule extends Base {

    /**
     * @desc 菜单列表
     * @return array
     */
    public function index() {
        $list = App::model('AuthRule')->getChildrenTree();
        return [
            'list'   => $list
        ];
    }

    /**
     * @desc 添加菜单
     * @param $params
     * @return array
     */
    public function add($params) {
        $category = App::model('AuthRule')->getChildrenTree();

        return [
            'params'   => $params,
            'category' => $category
        ];
    }

    /**
     * @desc 编辑菜单
     * @param $params
     * @return array
     */
    public function edit($params) {
        $list = App::model('AuthRule')
            ->where(['ar_id' => $params['id']])
            ->find();

        $controllerAction = explode('/', $list['ar_controller_action']);
        $list['controllerName'] = $controllerAction[0];
        $list['actionName'] = $controllerAction[1];

        $category = App::model('AuthRule')->getChildrenTree();

        return [
            'info'     => output_format($list, 'ar'),
            'params'   => $params,
            'category' => $category
        ];
    }

    /**
     * @desc 菜单编辑 (添加、编辑)
     * @param array $params
     * @return array|bool
     */
    public function operateAjax($params) {
        $data = [
            'ar_name'      => $params['name'],
            'ar_parent_id' => $params['parentId'],
            'ar_status'    => $params['status'],
            'ar_icon'      => $params['icon']
        ];

        if($params['controllerName'] && $params['actionName']) {
            $data['ar_controller_action'] = ucfirst($params['controllerName']).'/'.$params['actionName'];
        }
        if($params['action'] == 'add') {
            $result = App::model('AuthRule')->insertGetId($data);
        }else {
            $result = App::model('AuthRule')
                ->where(['ar_id' => $params['id']])
                ->update($data);
        }

        if($result === false) {
            $this->errorCode = EC_DATABASE_ERROR;
            return false;
        }
        return true;
    }

    /**
     * @desc 更新权限列表排序
     * @param $params
     * @return bool
     */
    public function updateSort($params) {
        $result = App::model('AuthRule')
            ->where(['ar_id' => $params['id']])
            ->update([
                'ar_sort' => $params['sort']
            ]);

        if($result === false) {
            $this->errorCode = EC_DATABASE_ERROR;
            return false;
        }
        return true;
    }

    /**
     * @desc 检查用户权访问
     * @param int $memberId 用户ID
     * @param string $controllerAction 控制器_方法
     * @return bool
     */
    public function checkAuth($memberId, $controllerAction) {
        $groupId = App::model('AuthMember')
            ->where(['am_member_id' => $memberId, 'am_status' => AUTH_MEMBER_STATUS_YES])
            ->value('am_group_id');

        //无需验证权限
        $filter = [
            'user_login',
            'user_dologin',
            'user_logout',
            'general_upload',
            'general_ueditor',
        ];
        if(in_array($controllerAction, $filter)) {
            return true;
        }

        //管理组无需验证
        if($groupId == 1) {
            return true;
        }

        $rules = App::model('AuthGroup')->where('ag_id', '=', $groupId)->value('ag_rules');
        if(!$rules) {
            return false;
        }
        $where = [
            ['ar_id', 'in', $rules],
            ['ar_status', '=', AUTH_RULE_STATUS_YES],
        ];
        $data = App::model('AuthRule')
            ->where($where)
            ->order('ar_sort desc,ar_id asc')
            ->column('ar_controller_action');

        $data = array_map('strtolower',$data);
        if(!in_array($controllerAction, $data)) {
            return false;
        }
        return true;
    }

    /**
     * @desc 获取用户对应的菜单
     * @param $memberId
     * @return array|bool
     */
    public function getMemberMenu($memberId) {
        $groupId = App::model('AuthMember')
            ->where('am_member_id', '=', $memberId)
            ->value('am_group_id');

        $rules = App::model('AuthGroup')->where('ag_id', '=', $groupId)->value('ag_rules');

        $where = [];
        if($groupId != 1) {
            $where = [
                ['ar_id', 'in', $rules],
                ['ar_status', '=', AUTH_RULE_STATUS_YES],
            ];
        }
        $field = [
            'ar_id as id',
            'ar_parent_id as parentId',
            'ar_controller_action as controllerAction',
            'ar_name as name',
            'ar_icon as icon',
        ];
        $data = App::model('AuthRule')
            ->field($field)
            ->where($where)
            ->order('ar_sort desc,ar_id asc')
            ->select();

        $menu = App::model('AuthRule')->getAuthChildren($data);
        return $menu;
    }
}